package com.example.websocketdemo.controller;

import com.example.websocketdemo.model.ChatMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

@Component  // 声明为Spring组件，由Spring容器管理
public class WebSocketEventListener {

    // 日志记录器
    private static final Logger logger = LoggerFactory.getLogger(WebSocketEventListener.class);

    // 注入消息发送模板
    @Autowired
    private SimpMessageSendingOperations messagingTemplate;

    // 处理WebSocket连接事件
    @EventListener
    public void handleWebSocketConnectListener(SessionConnectedEvent event) {
        logger.info("Received  a new web socket connection");
    }

    // 处理WebSocket断开连接事件
    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
        // 从事件中获取STOMP头信息
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());

        // 从会话属性中获取用户名
        String username = (String) headerAccessor.getSessionAttributes().get("username");

        if(username != null) {
            logger.info("User  Disconnected : " + username);

            // 创建离开消息
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setType(ChatMessage.MessageType.LEAVE);   // 设置消息类型为离开
            chatMessage.setSender(username);   // 设置发送者

            // 向"/topic/public"主题发送离开通知
            messagingTemplate.convertAndSend("/topic/public",  chatMessage);
        }
    }
}